<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        body {
            height: 2000px;
        }
        
        #btn {
            width: 50px;
            height: 50px;
            background: red;
            position: fixed;
            bottom: 100px;
            right: 100px;
            display: none;
        }
    </style>
</head>

<body>
    <div id="btn">返回顶部</div>

    <script>
        // document.onscroll = function() {
        //     if (document.documentElement.scrollTop > 300) {
        //         btn.style.display = "block";
        //     } else {
        //         btn.style.display = "none";
        //     }
        // }
        // btn.onclick = function() {
        //     var scrollTop = document.documentElement.scrollTop;
        //     document.documentElement.scrollTop = 0;
        // }
    </script>
    <script>
        window.onload = function() {
            var btn = document.getElementById('btn');
            var timer = null;
            var con = document.body;
            var bodyHeight = 300;
            //检测用户是否拖动了滚动条
            window.onscroll = function() {
                    var scrollTop = document.documentElement.scrollTop;
                    if (!timer) {
                        console.log(timer)
                        clearInterval(timer)
                    }
                    if (scrollTop <= bodyHeight) {
                        btn.style.display = "none";
                    } else {
                        btn.style.display = "block";
                    }
                }
                //用户点击了返回顶部
            btn.onclick = function() {
                timer = setInterval(function() {
                    //顶部距离
                    var scrollTop = document.documentElement.scrollTop;
                    // console.log(scrollTop)
                    var iSpeed = Math.floor(-scrollTop / 10);
                    //如果滚动到了顶部，清除定时器
                    if (scrollTop == 0) {
                        clearInterval(timer)
                    }
                    document.documentElement.scrollTop = scrollTop + iSpeed;
                }, 30)
                console.log(timer)
            }
        }
    </script>


</body>

</html>